package cn.qianxun.meta.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: 魏保停
 * @Date: 2023/09/26 21:06
 * @description:
 */

/**
 * configurator = MySpringConfigurator.class
 * 这个地方经验证不需用加上否则多设备连接回发现两台以上设备连接
 * 回造成下面的session变为同一个，造成其他设备推送失败，所以不要盲目复制别人的，要注意此处
 *
 * @author 魏保停
 */
@Slf4j
@Component
@ServerEndpoint(value = "/websocket/{userId}")
public class WebSocket {
    private static int onlineCount = 0;
    private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
    private Session session;
    private String userId;

    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) throws IOException {
        this.userId = userId;
        this.session = session;

        addOnlineCount();
        clients.put(userId+":"+session.getId(), this);
        log.info("WebSocKet已连接" + getOnlineCount());
    }

    @OnClose
    public void onClose() throws IOException {
        clients.remove(userId+":"+session.getId());
        subOnlineCount();
        log.info("WebSocKet已断开" + getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        // DataWrapper res = new DataWrapper();
        // System.out.println("message:" + message);
        // JSONObject req = JSONObject.parseObject(message);
        // 发送数据给服务端
        log.info("WebSocKet开始发送消息");
        sendMessageAll(message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    public void sendMessageTo(String message, String to) {
        if (!CollectionUtils.isEmpty(clients.values())) {
            for (WebSocket item : clients.values()) {
                if (item.userId.equals(to)) {
                    item.session.getAsyncRemote().sendText(message);
                    log.info("WebSocKet发送消息:"+message);
                }
            }
        }
    }

    public void sendMessageAll(String message){
        if (!CollectionUtils.isEmpty(clients.values())) {
            log.info("WebSocKet发送全部消息");
            for (WebSocket item : clients.values()) {
                item.session.getAsyncRemote().sendText(message);
            }
        }

    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
    }

    public static synchronized Map<String, WebSocket> getClients() {
        return clients;
    }

}
